package server.models;

import java.util.ArrayList;
import java.util.Date;
import java.util.Dictionary;
import java.util.Hashtable;

import server.doc.xml.XMLUserProfile;

import common.models.*;
import common.types.*;

public class UserStatus extends MvcModel {
	
	private static final long serialVersionUID = 1416887090465615634L;
	
	private static Dictionary<Integer, StatusType> onlineStatus = new Hashtable<Integer, StatusType>();
	private static Dictionary<Integer, Date> onlineTime = new Hashtable<Integer, Date>();
	private static ArrayList<Integer> onlineUsers = new ArrayList<Integer>();
	private static UserStatus statusPtr = null;
	
	public UserStatus() {
		if (statusPtr == null) {
			onlineStatus = new Hashtable<Integer, StatusType>();
			statusPtr = this;
		}
	}
	
	public StatusType getStatus(int uid) {
		StatusType status = onlineStatus.get(uid);
		if (status != null)
			return status;
		else {
			if (XMLUserProfile.getInstance().userExists(uid))
				return StatusType.offline;
			else
				throw new Error("User #" + Integer.toString(uid) + " doesn't exist");
		}
	}
	
	public void setStatus(int uid, StatusType status) {
		onlineStatus.put(new Integer(uid), status);
		if (status == StatusType.offline && onlineUsers.contains(new Integer(uid))) {
			onlineTime.remove(new Integer(uid));
			onlineUsers.remove(new Integer(uid));
		} else if (status == StatusType.online && !onlineUsers.contains(new Integer(uid))) {
			onlineTime.put(new Integer(uid), new Date());
			onlineUsers.add(new Integer(uid));
		}
	}
	
	/* delete the status while deleting the user
	 * 
	 */
	public void removeStatus(int uid) {
		StatusType s = onlineStatus.get(uid);
		if (s != null) {
			if (s == StatusType.online) {
				onlineTime.remove(new Integer(uid));
				onlineUsers.remove(new Integer(uid));
			}
			onlineStatus.remove(new Integer(uid));
		} else
			throw new Error("User doesn't exist");
	}
	
	public Date getOnlineTime(int uid) {
		Date time = onlineTime.get(new Integer(uid));
		if (time == null)
			throw new Error("User not online (or userID doesn't exist)");
		else
			return time;
	}
	
	public ArrayList<Integer> getOnlineUsers() { return onlineUsers; }
	
}
